﻿
using ETC.DLEDPositionTool.Core;
using ETC.DLEDPositionTool.Models;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Rect = OpenCvSharp.Rect;
using Size = OpenCvSharp.Size;


namespace ETC.DLEDPositionTool.Windows
{
    /// <summary>
    /// FrmPreview.xaml 的交互逻辑
    /// </summary>
    public partial class FrmPreview : Bandit.UI.BanditWindow
    {
        public string _ImagePath;
        //public delegate void SaveConfigHandler();
        //public event SaveConfigHandler OnSaveConfigChanged;
        public delegate void CloseFrmPreviewHandler();

        public event CloseFrmPreviewHandler CloseFrmPreviewChanged;

        public FrmPreview(string ImagePath)
        {
            InitializeComponent();

            this.Loaded += delegate
            {
                _ImagePath = ImagePath;
                this.PreViewImage(_ImagePath);
            };

            this.Closed += delegate
            {
                if (CloseFrmPreviewChanged != null)
                {
                    CloseFrmPreviewChanged();
                }
            };
        }

        public void ShowImage()
        {
            PreViewImage(_ImagePath);
        }

        private void PreViewImage(string imagePath)
        {
            //BitmapImage image = new BitmapImage(new Uri(ImagePath, UriKind.Absolute));//打开图片
            //PreviewImageName.Source = image;//将控件和图片绑定，logo为Image控件名称

            this.Loading.Show("Roi...");

            Task.Factory.StartNew(() =>
            {

                Mat srcImage = Cv2.ImRead(imagePath, ImreadModes.AnyColor);
                //Mat RoIImage =

                Cv2.CvtColor(srcImage, srcImage, ColorConversionCodes.GRAY2BGR);

                //srcImage = this.RotateAngleImage(srcImage, TestConfig.Instance.AngleValue);

                foreach (MyROIRect roiRect in TestConfig.Instance.ROIRectList)
                {

                    if (roiRect.IsEnable)
                    {
                        OpenCvSharp.Rect roi = new OpenCvSharp.Rect(roiRect.X, roiRect.Y, roiRect.Width, roiRect.Height);//首先要用个rect确定我们的兴趣区域在哪

                        Cv2.Rectangle(srcImage, roi, OpenCvSharp.Scalar.Red, 2);

                        foreach (MyROIRect singleRect in TestConfig.Instance.SingleROIRectList)
                        {
                            if (singleRect.IsEnable)
                            {
                                OpenCvSharp.Rect singleRoi = new OpenCvSharp.Rect(roiRect.X + singleRect.X, roiRect.Y + singleRect.Y, singleRect.Width, singleRect.Height);//首先要用个rect确定我们的兴趣区域在哪

                                Cv2.Rectangle(srcImage, singleRoi, OpenCvSharp.Scalar.Yellow, 2);
                            }
                        }
                    }
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    PreviewImageName.Source = MatToBitmapImage(srcImage);
                }));

            }).ContinueWith(t =>
            {
                this.Loading.Hide();

            });
        }

        public BitmapImage MatToBitmapImage(Mat image)
        {

            System.Drawing.Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);

            using (var ms = new MemoryStream())

            {

                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                BitmapImage result = new BitmapImage();

                result.BeginInit();

                result.CacheOption = BitmapCacheOption.OnLoad;

                result.StreamSource = ms;

                result.EndInit();

                return result;

            }

        }

        private void RefreshImage_OnClick(object sender, RoutedEventArgs e)
        {
            PreViewImage(_ImagePath);
        }

        /// <summary>
        /// 图片旋转
        /// </summary>
        /// <param name="srcImage"></param>
        /// <param name="angle"></param>
        /// <returns></returns>
        public Mat RotateAngleImage(Mat srcImage, double angle)
        {
            Mat resultImage = new Mat();
            if (srcImage != null)
            {
                float radian = (float)(angle / 180.0 * Cv2.PI);
                int maxBorder = (int)(Math.Max(srcImage.Cols, srcImage.Rows) * 1.414);
                int dx = (maxBorder - srcImage.Cols) / 2;
                int dy = (maxBorder - srcImage.Rows) / 2;
                Cv2.CopyMakeBorder(srcImage, resultImage, dy, dy, dx, dx, BorderTypes.Constant, OpenCvSharp.Scalar.White);


                //旋转
                Point2f center = new Point2f((float)(resultImage.Cols / 2), (float)(resultImage.Rows / 2));
                Mat affine_matrix = Cv2.GetRotationMatrix2D(center, angle, 1.0);//求得旋转矩阵
                Cv2.WarpAffine(resultImage, resultImage, affine_matrix, resultImage.Size());

                //计算图像旋转之后包含图像得最大的矩形
                double sinVal = Math.Abs(Math.Sin(radian));
                double cosVal = Math.Abs(Math.Cos(radian));

                Size targetSize = new Size((int)(srcImage.Cols * cosVal + srcImage.Rows * sinVal), (int)(srcImage.Cols * sinVal + srcImage.Rows * cosVal));

                //剪掉多余边框
                int x = (resultImage.Cols - targetSize.Width) / 2;
                int y = (resultImage.Rows - targetSize.Height) / 2;

                Rect rect = new Rect(x, y, targetSize.Width, targetSize.Height);

                resultImage = new Mat(resultImage, rect);
            }
            return resultImage;


        }
    }
}
